package com.example.musicmodule.util;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.musicmodule.Callback.Callback;
import com.example.musicmodule.entity.Music;

import java.util.List;


/**
 * Created by 王虎 on 2016/12/15.
 */

public class RequestUtil {
    String TAG = "cmj";

    private Context context;
    private Callback callback;
    public RequestQueue queue;

    public RequestUtil(Context context) {
        this.context = context;
        queue = Volley.newRequestQueue(context);
    }

    public RequestUtil(Context context, Callback callback) {
        this.context = context;
        this.callback = callback;
        queue = Volley.newRequestQueue(context);

    }

    public void getData(String url ){
        StringRequest request=new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                callback.callback(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }
    public void getData(final List<Music> list, final int position){
        String url=MusicUrlUtil.getMusicUrl(list.get(position).getSong_id());
        StringRequest request=new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                JSONObject object= JSON.parseObject(s);
                JSONObject bitrate= (JSONObject) object.get("bitrate");
                Music m=list.get(position);
                m.setUrl(bitrate.getString("file_link"));
                list.set(position,m);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        queue.add(request);
    }


}
